<template>
  <div class="registration-audit">
    <!-- 顶部操作栏 -->
    <div class="header-actions">
      <div class="left-actions">
        <el-button 
          type="success" 
          @click="handleBatchApprove"
          :disabled="selectedRegistrations.length === 0"
        >
          <el-icon><Check /></el-icon>
          批量通过
        </el-button>
        <el-button 
          type="warning" 
          @click="handleBatchReject"
          :disabled="selectedRegistrations.length === 0"
        >
          <el-icon><Close /></el-icon>
          批量拒绝
        </el-button>
      </div>
      <div class="right-actions">
        <el-button @click="handleExportAuditList">
          <el-icon><Download /></el-icon>
          导出审核列表
        </el-button>
      </div>
    </div>

    <!-- 搜索筛选区域 -->
    <el-card class="search-card" shadow="never">
      <el-form :model="searchForm" inline class="search-form">
        <el-form-item label="关键词">
          <el-input 
            v-model="searchForm.keyword" 
            placeholder="请输入运动员姓名、工号或项目名称"
            clearable
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item label="审核状态">
          <el-select v-model="searchForm.auditStatus" placeholder="请选择状态" clearable style="width: 140px;">
            <el-option label="全部" :value="null"/>
            <el-option label="待审核" :value="0"/>
            <el-option label="审核通过" :value="1"/>
            <el-option label="审核拒绝" :value="2"/>
          </el-select>
        </el-form-item>
        <el-form-item label="运动员">
          <el-select v-model="searchForm.athleteId" placeholder="请选择运动员" clearable filterable style="width: 160px;">
            <el-option 
              v-for="athlete in athletes" 
              :key="athlete.id" 
              :label="`${athlete.realName}(${athlete.workNumber})`" 
              :value="athlete.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="比赛项目">
          <el-select v-model="searchForm.eventId" placeholder="请选择项目" clearable filterable style="width: 160px;">
            <el-option 
              v-for="event in events" 
              :key="event.id" 
              :label="event.eventName" 
              :value="event.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 审核统计 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :span="6">
        <el-card shadow="never">
          <div class="stat-item">
            <div class="stat-value pending">{{ auditStats.pending }}</div>
            <div class="stat-label">待审核</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="never">
          <div class="stat-item">
            <div class="stat-value approved">{{ auditStats.approved }}</div>
            <div class="stat-label">已通过</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="never">
          <div class="stat-item">
            <div class="stat-value rejected">{{ auditStats.rejected }}</div>
            <div class="stat-label">已拒绝</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="never">
          <div class="stat-item">
            <div class="stat-value total">{{ auditStats.total }}</div>
            <div class="stat-label">总计</div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 报名审核列表 -->
    <el-card class="table-card" shadow="never">
      <el-table 
        :data="registrationList" 
        :loading="loading" 
        @selection-change="handleSelectionChange"
        stripe
        style="width: 100%"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="athleteName" label="运动员姓名" width="120" show-overflow-tooltip />
        <el-table-column prop="athleteNumber" label="学号" width="120" show-overflow-tooltip />
        <el-table-column prop="eventName" label="项目名称" width="160" show-overflow-tooltip />
        <el-table-column prop="eventCode" label="项目编码" width="120" show-overflow-tooltip />
        <el-table-column prop="registrationNumber" label="报名编号" width="120" show-overflow-tooltip />
        <el-table-column prop="teamName" label="团队名称" width="120" show-overflow-tooltip />
        <el-table-column prop="auditStatus" label="审核状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getAuditStatusTagType(row.auditStatus)">
              {{ getAuditStatusText(row.auditStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="registrationTime" label="报名时间" width="160">
          <template #default="{ row }">
            {{ formatDateTime(row.registrationTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="auditTime" label="审核时间" width="160">
          <template #default="{ row }">
            {{ formatDateTime(row.auditTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="auditRemark" label="审核备注" width="120" show-overflow-tooltip />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button 
              link 
              type="primary" 
              @click="handleViewDetail(row)"
            >
              查看详情
            </el-button>
            <el-button 
              link 
              type="success" 
              @click="handleAudit(row, 1)"
              v-if="row.auditStatus === 0"
            >
              通过
            </el-button>
            <el-button 
              link 
              type="warning" 
              @click="handleAudit(row, 2)"
              v-if="row.auditStatus === 0"
            >
              拒绝
            </el-button>
            <el-button 
              link 
              type="info" 
              @click="handleViewAuditHistory(row)"
              v-if="row.auditStatus !== 0"
            >
              审核记录
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页器 -->
      <div class="pagination-container">
        <el-pagination
          :current-page="pagination.current"
          :page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 详情对话框 -->
    <el-dialog v-model="detailDialogVisible" title="报名详情" width="800px">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="运动员姓名">{{ registrationDetail.athleteName || '-' }}</el-descriptions-item>
        <el-descriptions-item label="学号">{{ registrationDetail.studentNumber || registrationDetail.athleteNumber || '-' }}</el-descriptions-item>
        <el-descriptions-item label="性别">{{ getAthleteGenderText(registrationDetail.athleteGender) }}</el-descriptions-item>
        <el-descriptions-item label="院系">{{ registrationDetail.department || '-' }}</el-descriptions-item>
        <el-descriptions-item label="班级">{{ registrationDetail.className || registrationDetail.athleteClass || '-' }}</el-descriptions-item>
        <el-descriptions-item label="联系电话">{{ registrationDetail.phone || registrationDetail.athletePhone || '-' }}</el-descriptions-item>
        <el-descriptions-item label="比赛项目">{{ registrationDetail.eventName || '-' }}</el-descriptions-item>
        <el-descriptions-item label="项目编码">{{ registrationDetail.eventCode || '-' }}</el-descriptions-item>
        <el-descriptions-item label="项目类型">{{ getEventTypeText(registrationDetail.eventType) }}</el-descriptions-item>
        <el-descriptions-item label="性别限制">{{ getGenderLimitText(registrationDetail.genderLimit) }}</el-descriptions-item>
        <el-descriptions-item label="年龄分组">{{ registrationDetail.ageGroup || '-' }}</el-descriptions-item>
        <el-descriptions-item label="成绩单位">{{ registrationDetail.unit || '-' }}</el-descriptions-item>
        <el-descriptions-item label="比赛时间">{{ formatDateTime(registrationDetail.competitionTime) }}</el-descriptions-item>
        <el-descriptions-item label="比赛地点">{{ registrationDetail.venue || '-' }}</el-descriptions-item>
        <el-descriptions-item label="报名编号">{{ registrationDetail.registrationNumber || '-' }}</el-descriptions-item>
        <el-descriptions-item label="团队名称">{{ registrationDetail.teamName || '-' }}</el-descriptions-item>
        <el-descriptions-item label="审核状态">
          <el-tag :type="getAuditStatusTagType(registrationDetail.auditStatus)">
            {{ getAuditStatusText(registrationDetail.auditStatus) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="报名时间">{{ formatDateTime(registrationDetail.registrationTime) }}</el-descriptions-item>
        <el-descriptions-item label="报名状态">
          <el-tag :type="getStatusTagType(registrationDetail.status)">
            {{ getStatusText(registrationDetail.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="审核时间">{{ formatDateTime(registrationDetail.auditTime) }}</el-descriptions-item>
        <el-descriptions-item label="审核人">{{ registrationDetail.auditUserName || registrationDetail.auditorName || '-' }}</el-descriptions-item>
        <el-descriptions-item label="审核备注" :span="2">{{ registrationDetail.auditRemark || '-' }}</el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">{{ registrationDetail.remarks || '-' }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>

    <!-- 审核对话框 -->
    <el-dialog v-model="auditDialogVisible" title="审核报名" width="500px">
      <el-form ref="auditFormRef" :model="auditForm" :rules="auditFormRules" label-width="100px">
        <el-form-item label="审核结果" prop="auditStatus">
          <el-radio-group v-model="auditForm.auditStatus">
            <el-radio :label="1">通过</el-radio>
            <el-radio :label="2">拒绝</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="审核备注" prop="auditRemark">
          <el-input 
            v-model="auditForm.auditRemark" 
            type="textarea" 
            :rows="4"
            placeholder="请输入审核备注" 
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="auditDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleAuditSubmit" :loading="auditLoading">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 批量审核对话框 -->
    <el-dialog v-model="batchAuditDialogVisible" :title="batchAuditTitle" width="500px">
      <el-form ref="batchAuditFormRef" :model="batchAuditForm" :rules="batchAuditFormRules" label-width="100px">
        <el-form-item label="审核备注" prop="auditRemark">
          <el-input 
            v-model="batchAuditForm.auditRemark" 
            type="textarea" 
            :rows="4"
            placeholder="请输入审核备注" 
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="batchAuditDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleBatchAuditSubmit" :loading="batchAuditLoading">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useUserStore } from '@/stores/user'
import { 
  getEventRegistrationList, getRegistrationDetail, auditRegistration, batchAuditRegistrations
} from '@/api/registration'
import { getAthleteList } from '@/api/athlete'
import { getEventList } from '@/api/event'
import {
  Check, Close, Search, Refresh, Download
} from '@element-plus/icons-vue'

// 用户状态
const userStore = useUserStore()

// 响应式数据
const loading = ref(false)
const registrationList = ref([])
const selectedRegistrations = ref([])
const athletes = ref([])
const events = ref([])

// 审核统计
const auditStats = reactive({
  pending: 0,
  approved: 0,
  rejected: 0,
  total: 0
})

// 搜索表单
const searchForm = reactive({
  keyword: '',
  auditStatus: null,
  athleteId: null,
  eventId: null
})

// 分页信息
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 详情对话框
const detailDialogVisible = ref(false)
const registrationDetail = ref({})

// 审核对话框
const auditDialogVisible = ref(false)
const auditLoading = ref(false)
const auditFormRef = ref(null)
const currentAuditId = ref(null)

// 批量审核对话框
const batchAuditDialogVisible = ref(false)
const batchAuditLoading = ref(false)
const batchAuditFormRef = ref(null)
const batchAuditStatus = ref(1)

// 审核表单
const auditForm = reactive({
  auditStatus: 1,
  auditRemark: ''
})

// 批量审核表单
const batchAuditForm = reactive({
  auditRemark: ''
})

// 表单验证规则
const auditFormRules = {
  auditStatus: [
    { required: true, message: '请选择审核结果', trigger: 'change' }
  ],
  auditRemark: [
    { required: true, message: '请输入审核备注', trigger: 'blur' }
  ]
}

const batchAuditFormRules = {
  auditRemark: [
    { required: true, message: '请输入审核备注', trigger: 'blur' }
  ]
}

// 计算属性
const batchAuditTitle = computed(() => {
  const actionMap = {
    1: '批量通过审核',
    2: '批量拒绝审核'
  }
  return actionMap[batchAuditStatus.value] || '批量审核'
})

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return '-'
  return new Date(dateTime).toLocaleString('zh-CN')
}

// 获取审核状态文本
const getAuditStatusText = (auditStatus) => {
  const statusMap = {
    0: '待审核',
    1: '审核通过',
    2: '审核拒绝'
  }
  return statusMap[auditStatus] || '未知'
}

// 获取审核状态标签类型
const getAuditStatusTagType = (auditStatus) => {
  const typeMap = {
    0: 'warning',
    1: 'success',
    2: 'danger'
  }
  return typeMap[auditStatus] || ''
}

// 获取运动员性别文本
const getAthleteGenderText = (gender) => {
  const genderMap = {
    1: '男',
    2: '女'
  }
  return genderMap[gender] || '-'
}

// 获取项目类型文本
const getEventTypeText = (type) => {
  const typeMap = {
    1: '个人项目',
    2: '团体项目'
  }
  return typeMap[type] || '-'
}

// 获取性别限制文本
const getGenderLimitText = (limit) => {
  const limitMap = {
    0: '不限',
    1: '男子',
    2: '女子'
  }
  return limitMap[limit] || '-'
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    0: '已取消',
    1: '正常'
  }
  return statusMap[status] || '-'
}

// 获取状态标签类型
const getStatusTagType = (status) => {
  const typeMap = {
    0: 'danger',
    1: 'success'
  }
  return typeMap[status] || ''
}

// 加载报名列表
const loadRegistrationList = async () => {
  try {
    loading.value = true
    const params = {
      current: pagination.current,
      size: pagination.size,
      ...searchForm
    }
    const response = await getEventRegistrationList(params)
    registrationList.value = response.data.records || []
    pagination.total = response.data.total || 0
    
    // 计算统计数据
    updateAuditStats()
  } catch (error) {
    console.error('加载报名列表失败:', error)
    ElMessage.error('加载报名列表失败')
  } finally {
    loading.value = false
  }
}

// 更新审核统计
const updateAuditStats = () => {
  auditStats.total = registrationList.value.length
  auditStats.pending = registrationList.value.filter(item => item.auditStatus === 0).length
  auditStats.approved = registrationList.value.filter(item => item.auditStatus === 1).length
  auditStats.rejected = registrationList.value.filter(item => item.auditStatus === 2).length
}

// 加载运动员列表
const loadAthletes = async () => {
  try {
    const response = await getAthleteList({ current: 1, size: 1000, status: 1 })
    athletes.value = response.data.records || []
  } catch (error) {
    console.error('加载运动员列表失败:', error)
  }
}

// 加载比赛项目列表
const loadEvents = async () => {
  try {
    const response = await getEventList({ current: 1, size: 1000, status: 1 })
    events.value = response.data.records || []
  } catch (error) {
    console.error('加载比赛项目列表失败:', error)
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  loadRegistrationList()
}

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, {
    keyword: '',
    auditStatus: null,
    athleteId: null,
    eventId: null
  })
  handleSearch()
}

// 分页处理
const handleSizeChange = (size) => {
  pagination.size = size
  pagination.current = 1
  loadRegistrationList()
}

const handleCurrentChange = (current) => {
  pagination.current = current
  loadRegistrationList()
}

// 选择处理
const handleSelectionChange = (selection) => {
  selectedRegistrations.value = selection
}

// 查看详情
const handleViewDetail = async (row) => {
  try {
    const response = await getRegistrationDetail(row.id)
    registrationDetail.value = {
      ...row,
      ...response.data
    }
    detailDialogVisible.value = true
  } catch (error) {
    console.error('获取报名详情失败:', error)
    ElMessage.error('获取报名详情失败')
  }
}

// 审核报名
const handleAudit = (row, status) => {
  currentAuditId.value = row.id
  auditForm.auditStatus = status
  auditForm.auditRemark = ''
  auditDialogVisible.value = true
}

// 提交审核
const handleAuditSubmit = async () => {
  try {
    await auditFormRef.value.validate()
    auditLoading.value = true

    const auditData = {
      registrationId: currentAuditId.value,
      auditStatus: auditForm.auditStatus,
      auditRemark: auditForm.auditRemark
    }

    await auditRegistration(auditData)
    ElMessage.success('审核成功')
    auditDialogVisible.value = false
    loadRegistrationList()
  } catch (error) {
    console.error('审核失败:', error)
    ElMessage.error('审核失败: ' + (error.response?.data?.message || error.message))
  } finally {
    auditLoading.value = false
  }
}

// 批量通过
const handleBatchApprove = () => {
  batchAuditStatus.value = 1
  batchAuditForm.auditRemark = ''
  batchAuditDialogVisible.value = true
}

// 批量拒绝
const handleBatchReject = () => {
  batchAuditStatus.value = 2
  batchAuditForm.auditRemark = ''
  batchAuditDialogVisible.value = true
}

// 提交批量审核
const handleBatchAuditSubmit = async () => {
  try {
    await batchAuditFormRef.value.validate()
    batchAuditLoading.value = true

    const auditList = selectedRegistrations.value.map(item => ({
      registrationId: item.id,
      auditStatus: batchAuditStatus.value,
      auditRemark: batchAuditForm.auditRemark
    }))

    await batchAuditRegistrations(auditList)
    
    const action = batchAuditStatus.value === 1 ? '批量通过' : '批量拒绝'
    ElMessage.success(`${action}成功`)
    batchAuditDialogVisible.value = false
    loadRegistrationList()
  } catch (error) {
    console.error('批量审核失败:', error)
    ElMessage.error('批量审核失败: ' + (error.response?.data?.message || error.message))
  } finally {
    batchAuditLoading.value = false
  }
}

// 查看审核记录
const handleViewAuditHistory = (row) => {
  ElMessage.info('审核记录功能开发中...')
}

// 导出审核列表
const handleExportAuditList = () => {
  ElMessage.info('导出功能开发中...')
}

// 组件挂载时加载数据
onMounted(() => {
  loadRegistrationList()
  loadAthletes()
  loadEvents()
})
</script>

<style scoped>
.registration-audit {
  padding: 20px;
}

.header-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.left-actions,
.right-actions {
  display: flex;
  gap: 10px;
}

.search-card {
  margin-bottom: 20px;
}

.search-form {
  margin-bottom: 0;
}

.stats-row {
  margin-bottom: 20px;
}

.stat-item {
  text-align: center;
}

.stat-value {
  font-size: 32px;
  font-weight: bold;
  margin-bottom: 8px;
}

.stat-value.pending {
  color: #e6a23c;
}

.stat-value.approved {
  color: #67c23a;
}

.stat-value.rejected {
  color: #f56c6c;
}

.stat-value.total {
  color: #409eff;
}

.stat-label {
  color: #909399;
  font-size: 14px;
}

.table-card {
  margin-bottom: 20px;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
